package com.yaoandw.crawl.storage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil {
	private static Statement stmt;
	private static PreparedStatement ps;
	private static Connection conn;

	public static Connection getConnection() {
		try {
			if (conn == null || conn.isClosed()) {
				Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
				conn = DriverManager
						.getConnection("jdbc:derby:PAGEDB;create=true");
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Statement getStatement() {
		try {
			if (stmt == null || stmt.isClosed()) {
				conn = getConnection();
				stmt = conn.createStatement();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	public static PreparedStatement getPrepareStatement(String sql) {
		try {
			if (ps == null || ps.isClosed()) {
				conn = getConnection();
				ps = conn.prepareStatement(sql);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ps;
	}

	public static void close() {
		if (stmt != null)
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		if (conn != null)
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
	}
}
